import {useCallback, useEffect, useRef, useState} from "react";
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import {Picker, View, Text, Textarea, Button} from "@tarojs/components";
import {AtList, AtListItem, AtModal, AtModalAction, AtModalContent, AtModalHeader} from "taro-ui";
import {API_URL, TREATMENTS} from "@/config";
import styles from './index.module.scss';

interface PatientData {
  bedId: string;
  createTime: string;
  patientId: number;
  patientName: string;
  phoneNo: string;
  remark: string;
  treatmentIds: string;
}

export default function (){

  const [selectorChecked, setSelectorChecked] = useState('');
  const [list, setList] = useState<PatientData[]>([]);
  const [modalShow,setModalShow] = useState(false);
  const [remark,setRemark] = useState('');

  const getData = useCallback(async (key: string='')=>{
    const res = await Taro.request({
      url: API_URL+"/AllPatient",
      method:"POST",
      data:{
        pageSize: 999,
        pageIndex: 0,
        key
      }
    });
    setList(res.data.data.data);
  }, []);

  useEffect(() => {
    getData();
  }, [getData]);

  function onChange(e){
    const value = TREATMENTS[e.detail.value].value;
    setSelectorChecked(value);
    getData(value);
  }


  const currentEditPatient = useRef<any>();
  function onEdit(patient: PatientData){
    currentEditPatient.current = patient;
    setRemark(patient.remark);
    setModalShow(true);
  }

  async function onDelete(patient: PatientData){
    const res = await Taro.showModal({
      title: '提示',
      content: '是否删除该病人',
    });

    if(res.confirm){
      currentEditPatient.current = patient;
      const delRes = await Taro.request({
        url: API_URL+ `/Delete?PatientId=${patient.patientId}`,
        method: 'POST',
      });
      if(delRes.data.data){
        getData(selectorChecked);
        await Taro.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 1000
        });
      }
    }
  }

  async function onConfirm(){
    try{
      Taro.showLoading();
      const res = await Taro.request({
        url: API_URL+ '/Update',
        method: 'POST',
        data: {
          patientId: currentEditPatient.current.patientId,
          remark
        }
      });
      if(res.data.data){
        setModalShow(false);
        getData(selectorChecked);
        await Taro.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 1000
        });
      }else{
        await Taro.showToast({
          title: '修改失败',
          icon: 'error',
          duration: 1000
        });
      }
    }catch (e){
      await Taro.showToast({
        title: '修改失败',
        icon: 'error',
        duration: 1000
      });
    }finally {
      Taro.hideLoading();
    }
  }

  return (
    <View className={styles.cureWrapper}>
      <Picker mode='selector' rangeKey='label' range={TREATMENTS} onChange={onChange}>
        <AtList>
          <AtListItem
            title='治疗选项'
            extraText={TREATMENTS.find(item=>item.value===selectorChecked)?.label || ''}
          />
        </AtList>
      </Picker>
      <View className={styles.cardWrapper}>
        {
          list.map(item=>(
            <View className={styles.card} key={item.patientId}>
              <View className={styles.cardHeader}>
                <Text>姓名：{item.patientName}</Text>
                <Text>床号：{item.bedId}</Text>
              </View>
              <View className={styles.cardBody}>
                治疗：{TREATMENTS.filter(treatment=>item.treatmentIds.split(',').includes(treatment.value)).map(el=>el.label).join('、')}
              </View>
              <View className={styles.cardFooter}>
                <View className={styles.remark}>备注信息：{item.remark || '无'}</View>
                <View className={styles.btn} onClick={()=>onEdit(item)} >查看编辑</View>
                <View className={classNames(styles.btn, styles.danger)} onClick={()=>onDelete(item)} >删除病人</View>
              </View>
            </View>
          ))
        }

        {!list.length && <h6 className={styles.noData}>暂无数据</h6>}
      </View>
      <AtModal
        isOpened={modalShow}
        closeOnClickOverlay={false}
      >
        <AtModalHeader>备注信息</AtModalHeader>
        <AtModalContent>
          <Textarea
            value={remark}
            onInput={e=>setRemark(e.detail.value)}
            placeholder='请填写备注'
          />
        </AtModalContent>
        <AtModalAction>
          <Button onClick={()=>setModalShow(false)}>取消</Button>
          <Button onClick={onConfirm}>确定</Button>
        </AtModalAction>
      </AtModal>
    </View>
  );
}
